package com.sunthy.mall.controller.admin;

import com.alibaba.druid.util.StringUtils;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.sun.xml.internal.bind.v2.model.core.ID;
import com.sunthy.mall.model.admin.Result;
import com.sunthy.mall.model.admin.bo.order.OrderChangeBo;
import com.sunthy.mall.model.admin.bo.order.OrdersByPageBO;
import com.sunthy.mall.model.admin.vo.order.OrderByIdInfoVo;
import com.sunthy.mall.model.admin.vo.order.OrdersByPageVO;
import com.sunthy.mall.service.admin.order.OrderService;
import com.sunthy.mall.service.admin.order.OrderServiceImpl;
import com.sunthy.mall.utils.HttpUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/api/admin/order/*")
public class OrderServlet extends HttpServlet {

    private Gson gson = new Gson();

    private OrderService orderService = new OrderServiceImpl();

    //如果不晓得如何打断点，那么就在程序的入口处打断点
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace(request.getContextPath() + "/api/admin/order/", "");
        if ("ordersByPage".equals(action)) {
            ordersByPage(request, response);
        } else if ("changeOrder".equals(action)) {
            changeOrder(request, response);
        }
    }

    /********
     * 提交修改订单的逻辑
     *  1.接收请求参数
     *  2.修改数据
     *  3.返回结果
     * @param request
     * @param response
     */
    private void changeOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String requestBody = HttpUtils.getRequestBody(request);
        // 封装成OrderChange bean类
        OrderChangeBo orderChangeBo = null;
        try {
            orderChangeBo = gson.fromJson(requestBody, OrderChangeBo.class);
        } catch (JsonSyntaxException e) {
            response.getWriter().println(gson.toJson(Result.error("请求参数不合法")));
            return;
        }
        if (orderChangeBo.getId() == null || orderChangeBo.getState() == null || orderChangeBo.getSpec() == null || orderChangeBo.getNum() == null) {
            response.getWriter().println(gson.toJson(Result.error("请求参数不合法")));
            return;
        }
        // 更改数据
        int code = orderService.orderChange(orderChangeBo);
        // 返回结果
        if (code == 0) {// 成功
            response.getWriter().println(gson.toJson(Result.ok()));
        } else if (code == 100) {
            response.getWriter().println(gson.toJson(Result.error("订单状态不可往回更改")));
        } else if (code == 200) {
            response.getWriter().println(gson.toJson(Result.error("只有未付款的订单可以修改规格")));
        } else if (code == 300){
            response.getWriter().println(gson.toJson(Result.error("该规格商品的数量不够啦")));
        } else if (code == 500){
            response.getWriter().println(gson.toJson(Result.error("更改数据异常")));
        }else {
            response.getWriter().println(gson.toJson(Result.error("更改数据异常")));
        }
    }

    /**
     * 按照页面展示order:
     * 1.接收请求参数
     * 2.查询order
     * 3.返回结果
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void ordersByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String requestBody = HttpUtils.getRequestBody(request);
        OrdersByPageBO ordersByPageBO = gson.fromJson(requestBody, OrdersByPageBO.class);
        //判断 金额上下限可以不填，但是如果填的话，那么一定要求是数字
        try {
            if (!StringUtils.isEmpty(ordersByPageBO.getMoneyLimit1())) {
                Double.parseDouble(ordersByPageBO.getMoneyLimit1());
            }
            if (!StringUtils.isEmpty(ordersByPageBO.getMoneyLimit2())) {
                Double.parseDouble(ordersByPageBO.getMoneyLimit2());
            }
        } catch (Exception e) {
            response.getWriter().println(gson.toJson(Result.error("金额必须是数字")));
            return;
        }
        OrdersByPageVO orders = orderService.ordersByPage(ordersByPageBO);
        response.getWriter().println(gson.toJson(Result.ok(orders)));
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if ("/order".equals(pathInfo)) {
            order(request, response);
        } else if ("/deleteOrder".equals(pathInfo)) {
            deleteOrder(request, response);
        }
    }

    /***********
     * 删除订单的逻辑：
     *  1.接收请求参数
     *  2.删除的订单
     *  3.返回结果
     * @param request
     * @param response
     */
    private void deleteOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String idStr = request.getParameter("id");
        Integer id = null;
        try {
            id = Integer.parseInt(idStr);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        // 校验参数
        if (id == null) {
            response.getWriter().println(gson.toJson(Result.error("参数错误")));
            return;
        }
        // 删除订单
        int code = orderService.orderDeleteById(id);
        // 返回结果
        if (code == 0) {
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("不能删除已购买的的订单")));
    }

    /*******
     * 编辑订单的回显逻辑：
     *  1.接收请求参数
     *  2.查询数据
     *  3.返回结果
     * @param request
     * @param response
     */
    private void order(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String idStr = request.getParameter("id");
        int id = 0;
        try {
            if (idStr != null) {
                id = Integer.parseInt(idStr);
            }
        } catch (NumberFormatException e) {
            response.getWriter().println(gson.toJson(Result.error("参数不合法！")));
            return;
        }
        // 查询数据
        OrderByIdInfoVo orderByIdInfoVo = orderService.orderByIdInfo(id);
        // 返回结果
        if (orderByIdInfoVo != null) {// 成功
            response.getWriter().println(gson.toJson(Result.ok(orderByIdInfoVo)));
            return;
        }// 失败
        response.getWriter().println(gson.toJson(Result.error("错误异常")));
    }
}
